<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>移动画布</title>
</head>

<body>
  <canvas id="canvasBox" width="600" height="600" style="border: 1px solid #ccc;"></canvas>

  <script src="../../script/fabric.js"></script>
  <script>
    // 官方案例
    // http://fabricjs.com/fabric-intro-part-5
    const canvas = new fabric.Canvas('canvasBox')

    fabric.Image.fromURL('../../images/bg.jpg', img => {
      canvas.setBackgroundImage(img)
      canvas.renderAll()
    })

    canvas.on('mouse:down', function (opt) {
      var evt = opt.e;
      if (evt.altKey === true) {
        this.isDragging = true
        this.selection = false
        this.lastPosX = evt.clientX
        this.lastPosY = evt.clientY
      }
    })
    canvas.on('mouse:move', function (opt) {
      if (this.isDragging) {
        var e = opt.e;
        var vpt = this.viewportTransform;
        vpt[4] += e.clientX - this.lastPosX
        vpt[5] += e.clientY - this.lastPosY
        this.requestRenderAll()
        this.lastPosX = e.clientX
        this.lastPosY = e.clientY
      }
    })
    canvas.on('mouse:up', function (opt) {
      // on mouse up we want to recalculate new interaction
      // for all objects, so we call setViewportTransform
      this.setViewportTransform(this.viewportTransform)
      this.isDragging = false
      this.selection = true
    })
  </script>
</body>

</html>